#include "webchannel.h"
#include "md5.h"
#include "sqlconn.h"

webChannel::webChannel(QObject *parent) : QObject(parent)
{
    recentUsr = "";
    recentPsd = "";
}

void webChannel::setSendText(const QString &text)
{
    s_text = text;
    emit sendText(s_text);
}

void webChannel::receiveText(const QString &r_text)
{
   QString message = r_text;
   if(message.contains(","))
   {
       QStringList li = message.split(",");
       if(li.length() < 2)
       {
           qDebug() <<  "wrong message:" << message;
           return;
       }
       validate(li[0],li[1]);
   }
   else
   {
      validate(message);
   }
}

void webChannel::validate(const QString usrname, const QString psd )
{
    QString sqlstr = "SELECT * FROM userprofile WHERE usr = '";
    sqlstr.append(usrname).append("'");
    sqlConn *con = new sqlConn(QCoreApplication::applicationDirPath()+"/settings/conf.ini");
    con->connect();
    if(psd != "null")
    {
        if(usrname != recentUsr)
        {
            recentUsr = usrname ;
            QSqlQuery* query = con->queryData(sqlstr);
            //get the psd  recentPsd = ? may not exist
            if(query->next())
                recentPsd = query->value(2).toString();
        }
        char*  psdstr;
        QByteArray ba = psd.toLatin1();
        psdstr = ba.data();
        MD5 *psdmd5 = new MD5(psdstr);
        QString qpsd(psdmd5->queryMD5());
        if (qpsd != recentPsd)
            setSendText("wrong");
        else
        {
            setSendText("ok");
            emit loginFinished();
        }
    }
    else
    {
        QSqlQuery* query = con->queryData(sqlstr);
        //validate the usrname
        if(query->next())
            setSendText("ok");
        else
            setSendText("wrong");
    }
    con->close();
}
